const https = require("https");
const http = require("http");
const qs = require("querystring");
const _url = require("url");

module.exports = function(url, ops){
    const request = url.includes("https") ? https : http;
    const cookie = qs.stringify(ops.cookie, ",").split(",");

    url = _url.parse(url);

    return new Promise((resolve)=>{
        const req = request.request({
            hostname: url.hostname,
            path: url.pathname,
            port: request === https ? 443 : 80,
            method: "POST",
            headers:{
                "Content-Type": "application/x-www-form-urlencoded",
                "Cookie": cookie
            }
        }, (res)=>{
            let str = "";
            res.on("data",(chunk)=>{
                str += chunk;
            })
            res.on("end",()=>{
                const cookie = [];
                res.rawHeaders.forEach((val, idx, self)=>{
                    if(val === "Set-Cookie"){
                        const oneCookie = self[idx+1].split("; ");
                        const obj = {};
                        oneCookie.forEach((val,idx)=>{
                            const item = val.split("=");
                            if(idx === 0){
                                obj.key = item[0];
                                obj.value = item[1];
                            }else{
                                obj[item[0]] = item[1];
                            }
                        })
                        obj.Expires = obj.Expires ? new Date(obj.Expires) : new Date();
                        cookie.push(obj)
                    }
                })
                resolve({
                    data:str,
                    cookie:cookie
                });
            })
        });
        req.write(qs.stringify(ops.data));
        req.end();
    })
}
